/**
 * Copyright © 2021-2025 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.organization.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.jeeplus.aop.logging.annotation.ApiLog;
import com.jeeplus.common.utils.UploadUtils;
import com.jeeplus.core.excel.EasyExcelUtils;
import com.jeeplus.core.excel.ExcelOptions;
import com.jeeplus.core.excel.annotation.ExportMode;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.organization.domain.OfficeRequest;
import com.jeeplus.organization.service.OfficeRecordService;
import com.jeeplus.organization.service.OfficeRequestService;
import com.jeeplus.organization.service.dto.BossDTO;
import com.jeeplus.organization.service.dto.OfficeRequestDTO;
import com.jeeplus.organization.service.mapstruct.OfficeRequestWrapper;
import com.jeeplus.organization.util.BlankDocument;
import com.jeeplus.organization.util.FileClassify;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;

/**
 * 请示稿件Controller
 * @author 淋漓
 * @version 2024-06-16
 */

@Api(tags ="请示稿件")
@RestController
@RequestMapping(value = "/office/request")
public class OfficeRequestController {

	@Autowired
	private OfficeRequestService officeRequestService;

	@Autowired
	private OfficeRequestWrapper officeRequestWrapper;

	/**
	 * 请示稿件列表数据
	 */
	@ApiLog("查询请示稿件列表数据")
	@ApiOperation(value = "查询请示稿件列表数据")
	@PreAuthorize("hasAuthority('office:request:list')")
	@GetMapping("list")
	public ResponseEntity<List<OfficeRequest>> list(String id) throws Exception {
		List<OfficeRequest> list = officeRequestService.list(new LambdaQueryWrapper<OfficeRequest>()
				.eq(OfficeRequest::getUserId, id)
				.like(OfficeRequest::getClassify, FileClassify.MANUSCRIPT));
		return ResponseEntity.ok (list);
	}
	/**
	 * 请示稿件列表数据
	 */
	@ApiLog("查询请示稿件列表数据")
	@ApiOperation(value = "查询请示稿件列表数据")
	@PreAuthorize("hasAuthority('office:request:page')")
	@GetMapping("page")
	public ResponseEntity<IPage<OfficeRequestDTO>> pageList(OfficeRequestDTO officeRequestDTO, Page<OfficeRequestDTO> page) throws Exception {
		IPage<OfficeRequestDTO> result;
		result= officeRequestService.MyPage(page, officeRequestDTO.getUserName(), officeRequestDTO.getApproverId(), officeRequestDTO.getUserId() , officeRequestDTO.getStatus(),officeRequestDTO.getTitle());
		return ResponseEntity.ok (result);
	}

	/**
	 * 根据Id获取请示稿件数据
	 */
	@ApiLog("根据Id获取请示文件数据")
	@ApiOperation(value = "根据Id获取请示文件数据")
	@PreAuthorize("hasAnyAuthority('office:request:view')")
	@GetMapping("queryById")
	public ResponseEntity queryById(String id) {
		if(BlankDocument.NEW_FILE.equals(id)){
			return ResponseEntity.ok(new OfficeRequestDTO());
		}
		OfficeRequest request = officeRequestService.getById(id);
		if(request==null){
			return ResponseEntity.badRequest().body("文件不存在");
		}
		return ResponseEntity.ok ( officeRequestWrapper.toDTO ( request ) );
	}

	/**
	 * 根据Id获取请示稿件数据
	 */
	@ApiLog("根据Id获取请示文件数据")
	@ApiOperation(value = "根据Id获取请示文件数据")
	@PreAuthorize("hasAnyAuthority('office:request:view')")
	@GetMapping("selectById")
	public ResponseEntity SelectById(String id) {
		OfficeRequestDTO officeRequestDTO = officeRequestService.SelectById(id);
		if(officeRequestDTO==null){
			return ResponseEntity.badRequest().body("数据异常");
		}
		return ResponseEntity.ok ( officeRequestDTO );
	}

	/**
	 * 根据Id获取请示稿件数据
	 */
	@ApiLog("根据Id获取负责人列表")
	@ApiOperation(value = "根据Id获取负责人列表")
	@GetMapping("selectPostById")
	public ResponseEntity selectPostById(String id) {
		if(id.isEmpty()){
			return ResponseEntity.badRequest().body("数据异常");
		}
		List<BossDTO> bossDTOS = officeRequestService.selectPostById(id);
		return ResponseEntity.ok (bossDTOS);
	}

	/**
	 * 保存请示稿件
	 */
	@ApiLog("保存请示稿件")
	@ApiOperation(value = "保存请示稿件")
	@PreAuthorize("hasAnyAuthority('office:request:add')")
	@PostMapping("save")
	@Transactional
	public  ResponseEntity <String> save(@Valid @RequestBody OfficeRequestDTO officeRequestDTO) {
		int list = officeRequestService.count(new LambdaQueryWrapper<OfficeRequest>()
				.eq(OfficeRequest::getUserId, officeRequestDTO.getUserId())
				.like(OfficeRequest::getClassify,FileClassify.MANUSCRIPT));
		if(list>10){
			return ResponseEntity.badRequest().body("稿件达到上限");
		}
		//新增或编辑表单保存
		officeRequestService.saveOrUpdate (officeRequestWrapper.toEntity (officeRequestDTO));
		return ResponseEntity.ok ( "保存草稿成功" );
	}

	/**
	 * 保存请示稿件
	 */
	@CrossOrigin(origins = "*")
	@ApiLog("保存请示稿件")
	@ApiOperation(value = "保存请示稿件")
//	@PreAuthorize("hasAnyAuthority('office:request:add')")
	@PostMapping("upload")
	@Transactional
	public  ResponseEntity <String> upload(@RequestParam("userId") String userId,@RequestParam("name") String name, @RequestParam("file") MultipartFile file) throws Exception {
		if(!file.isEmpty()){
			String filePath = UploadUtils.requestUpload(file);
			OfficeRequest request = new OfficeRequest();
			//根据用户id和文件名查询
			request.setAttachment(filePath);
			officeRequestService.update(request, new LambdaQueryWrapper<OfficeRequest>().eq(OfficeRequest::getUserId, userId).eq(OfficeRequest::getName, name));
			return ResponseEntity.ok ( "保存草稿成功" );
		}
		return ResponseEntity.badRequest().body("文件异常");
	}
	/**
	 * 删除请示稿件
	 */
	@ApiLog("删除请示稿件")
	@ApiOperation(value = "删除请示稿件")
	@PreAuthorize("hasAuthority('office:request:del')")
	@DeleteMapping("delete")
	public ResponseEntity <String> delete(String ids) {
		String idArray[] = ids.split(",");
        officeRequestService.removeByIds ( Lists.newArrayList ( idArray ) );
		return ResponseEntity.ok( "删除成功" );
	}



    /**
     * 导出请示稿件数据
     *
     * @param officeRequestDTO
     * @param page
     * @param response
     * @throws Exception
     */
    @ApiLog("导出请示稿件数据")
    @PreAuthorize("hasAnyAuthority('request:officeRequest:export')")
    @GetMapping("export")
    public void exportFile(OfficeRequestDTO officeRequestDTO, Page <OfficeRequest> page, ExcelOptions options, HttpServletResponse response) throws Exception {
        String fileName = options.getFilename ( );
		QueryWrapper queryWrapper = QueryWrapperGenerator.buildQueryCondition (officeRequestDTO, OfficeRequestDTO.class);
        if ( ExportMode.current.equals ( options.getMode ( ) ) ) { // 导出当前页数据

        } else if ( ExportMode.selected.equals ( options.getMode ( ) ) ) { // 导出选中数据
            queryWrapper.in ( "id", options.getSelectIds () );
        } else { // 导出全部数据
            page.setSize ( -1 );
            page.setCurrent ( 0 );
        }
        List < OfficeRequest> result = officeRequestService.page ( page, queryWrapper ).getRecords ( );
        EasyExcelUtils.newInstance ( officeRequestService, officeRequestWrapper ).exportExcel ( result,  options.getSheetName ( ), OfficeRequestDTO.class, fileName,options.getExportFields (), response );
    }

    /**
     * 导入请示稿件数据
     *
     * @return
     */
    @PreAuthorize("hasAnyAuthority('request:officeRequest:import')")
    @PostMapping("import")
    public ResponseEntity importFile(MultipartFile file) throws IOException {
        String result = EasyExcelUtils.newInstance ( officeRequestService, officeRequestWrapper ).importExcel ( file, OfficeRequestDTO.class );
        return ResponseEntity.ok ( result );
    }

    /**
     * 下载导入请示稿件数据模板
     *
     * @param response
     * @return
     */
    @PreAuthorize ("hasAnyAuthority('request:officeRequest:import')")
    @GetMapping("import/template")
    public void importFileTemplate(HttpServletResponse response) throws IOException {
        String fileName = "请示稿件数据导入模板.xlsx";
        List<OfficeRequestDTO> list = Lists.newArrayList();
        EasyExcelUtils.newInstance ( officeRequestService, officeRequestWrapper ).exportExcel ( list,  "请示稿件数据", OfficeRequestDTO.class, fileName, null, response );
    }


}
